library jm_flutter;

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_i18n/flutter_i18n.dart';
import 'package:get/get.dart';
import 'package:jm_flutter/src/config.dart';
import 'package:jm_flutter/src/ui/routers/jm_page.dart';
import 'package:jm_flutter/src/ui/routers/routes.dart';
import 'package:jm_flutter/src/ui/ui.dart';
import 'package:jm_flutter_common/jm_flutter_common.dart';
import 'package:path_provider/path_provider.dart';
import 'package:universal_io/io.dart';
import 'src/common/common.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'src/common/utils/device_info.dart';

export 'src/common/common.dart';
export 'src/ui/ui.dart';
export 'src/config.dart';

export 'package:get/get.dart' hide Response, MultipartFile, FormData;
export 'package:jm_flutter_common/jm_flutter_common.dart';

class JmApp extends StatelessWidget {
  JmApp({
    Key? key,
    this.home,
    this.initPage,
    this.debugShowCheckedModeBanner = false,
    this.pages,
    this.onInit,
  }) : super(key: key) {
    init();
  }

  final tag = "JmMaterialApp";
  final Widget? home;
  final String? initPage;
  final bool debugShowCheckedModeBanner;
  final List<JmPage>? pages;
  final VoidCallback? onInit;

  void init() {
    logd(tag, "开始初始化");
    //打印当前设备的操作系统
    logd(tag,
        "当前设备的操作系统:${Platform.operatingSystem}, 版本:${Platform.operatingSystemVersion}, 运行环境:${kIsWeb ? "Web" : "Native"}");
    getApplicationDocumentsDir().then((value) {
      JmConfig.appDocPath = value.path;
      logd(tag, "appDocPath:${JmConfig.appDocPath}");
    });
    getTemporaryDirectory().then((value) {
      JmConfig.appTempPath = value.path;
      JmConfig.appCachePath = value.path.replaceAll("Library/Caches", "tmp");
      logd(tag, "appTempPath:${JmConfig.appTempPath}");
      logd(tag, "appCachePath:${JmConfig.appCachePath}");
    });

    I18n.init();
    if (pages != null && pages!.isNotEmpty) {
      for (var page in pages!) {
        JmPages.pages.add(GetPage(name: page.name, page: () => page.page));
        logv(tag, "添加页面：${page.name} ,${JmPages.pages.length}");
      }
    } else {
      logv(tag, "未添加页面");
    }

    //AppVersion.init();
    initUi(
        colors: JmConfig.colors,
        assets: JmConfig.assets,
        statusBarType: JmConfig.statusBarType);
    Show.init();
  }

  @override
  Widget build(BuildContext context) {
    MyScreen.init(context);
    //init();
    //AppVersion.init();
    return MediaQuery(
      data: MediaQuery.of(context).copyWith(textScaler: TextScaler.noScaling),
      child: GetMaterialApp(
        onInit: () async {
          logv("Get", "onInit");
          if (!kIsWeb) {
            AppVersion.init();
          }
          await MyDeviceInfo.init();
          onInit?.call();
        },
        home: home,
        title: JmConfig.appName,
        enableLog: false,
        theme: ThemeData(
            // Define the default brightness and colors.
            //brightness: Brightness.dark,
            //primaryColor: Colors.red[800],
            colorScheme: ColorScheme.fromSeed(
              seedColor: JmConfig.colors.main,
            ),
            primaryColor: JmConfig.colors.main,

            // Define the default font family.
            fontFamily: JmConfig.defTextStyle.fontFamily,

            // Define the default `TextTheme`. Use this to specify the default
            // text styling for headlines, titles, bodies of text, and more.
            // textTheme: const TextTheme(
            //   headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
            //   headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
            //   bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
            // ),
            useMaterial3: true),
        initialRoute: initPage,
        builder: EasyLoading.init(
            builder: I18n.initBuilder(FlutterI18n.rootAppBuilder())),
        localizationsDelegates: [
          I18n.delegateOf(context),
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate
        ],
        logWriterCallback: (String text, {bool? isError}) {
          String pageName = "";
          if (text.contains("GOING TO ROUTE")) {
            pageName = text.substring(15);
            logv("Get", ">>>进入页面:$pageName");
          } else if (text.contains("CLOSE TO ROUTE")) {
            pageName = text.substring(15);
            logv("Get", "<<<退出页面:$pageName");
          } else if (text.contains("OPEN DIALOG")) {
          } else if (text.contains("CLOSE DIALOG")) {
          } else {
            logv("Get", text);
          }
        },
        debugShowCheckedModeBanner: debugShowCheckedModeBanner,
        getPages: JmPages.pages,
      ),
    );
  }
}

class JmFlutter {
  static String get appName => JmConfig.appName;

  static void run() async {
    if (!kIsWeb) {
      await Storage.init();
    }

    runApp(
      JmApp(
        initPage: JmConfig.initPage,
        pages: JmConfig.pages,
        home: JmConfig.homeWidget,
      ),
    );
  }
}
